import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: []
    }),
    actions: {
      // 登录
      login(userInfo) {
        const username = userInfo.username.trim()
        const password = userInfo.password
        const code = userInfo.code
        const uuid = userInfo.uuid
        // 判断是否是管理员登录
        const isAdmin = window.location.pathname.includes('/admin')
        return new Promise((resolve, reject) => {
          login(username, password, code, uuid).then(res => {
            setToken(res.token)
            this.token = res.token
            // 登录成功后立即获取用户信息
            this.getInfo().then(() => {
              resolve()
              // 添加页面刷新
              setTimeout(() => {
                window.location.reload()
              }, 100)
            }).catch(error => {
              reject(error)
            })
          }).catch(error => {
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            console.log('获取到的用户信息:', user)
            
            // 处理头像URL
            let avatar = user.avatar || ""
            console.log('原始头像URL:', avatar)
            
            if (!isHttp(avatar)) {
              if (isEmpty(avatar)) {
                avatar = defAva
                console.log('使用默认头像:', avatar)
              } else {
                // 确保avatar路径以/profile开头
                if (!avatar.startsWith('/profile')) {
                  avatar = '/profile' + avatar
                }
                // 拼接完整URL，移除可能的重复/dev-api前缀
                const baseApi = import.meta.env.VITE_APP_BASE_API.replace(/\/+$/, '')
                avatar = baseApi + avatar
                console.log('处理后的头像URL:', avatar)
              }
            }
            
            this.id = user.userId
            this.name = user.userName
            this.avatar = avatar
            console.log('更新到store的头像URL:', this.avatar)
            
            if (res.roles && res.roles.length > 0) {
              this.roles = res.roles
              this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            // 判断是否是管理员
            const isAdmin = window.location.pathname.includes('/admin')
            if (isAdmin && !this.roles.includes('admin')) {
              reject('该用户没有管理员权限')
              return
            }
            resolve(res)
          }).catch(error => {
            console.error('获取用户信息失败:', error)
            reject(error)
          })
        })
      },
      // 退出系统
      logOut() {
        return new Promise((resolve, reject) => {
          logout().then(() => {
            this.token = ''
            this.roles = []
            this.permissions = []
            removeToken()
            // 判断当前路径是否包含admin，如果是则重定向到管理员登录页
            const currentPath = window.location.pathname
            if (currentPath.includes('/admin')) {
              resolve('/admin/login')
            } else {
              resolve('/user/login')
            }
          }).catch(error => {
            reject(error)
          })
        })
      }
    }
  })
export default useUserStore

